package spring.lottery.server.activityStatus.imp;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spring.lottery.common.exception.ServerException;
import spring.lottery.server.DrawPrizeServer;
import spring.lottery.server.activityStatus.ActivityStatusManager;
import spring.lottery.server.activityStatus.operate.AbstractOperate;
import spring.lottery.controller.param.DrawPrizesData;
import spring.lottery.server.exceptionCode.ServerConstantCode;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Service
public class ActivityStatusManagerImp implements ActivityStatusManager {

    /**
     * 这样注入的话，他会把所有的实现了AbstractOperate这个类的交给spring管理的实现类给注入到map中
     * 责任链
     */
    @Autowired
    Map<String, AbstractOperate> operateMap = new HashMap<String, AbstractOperate>();

    @Autowired
    DrawPrizeServer drawPrizeServer;

    @Override
    public void convert(DrawPrizesData param) {

        if (operateMap.isEmpty()) {
            log.info("operateMap is empty");
            return;
        }

        Map<String, AbstractOperate> map = new HashMap<>(operateMap);

        //先对人员奖品进行扭转
        Boolean update = convertEvent(param, map, 1);

        //再对活动扭转
        update = convertEvent(param, map, 2) || update;

        if (update) {
            //扭转成功，把redis中的也给跟新了
            drawPrizeServer.updateRedis(param);

            log.info("活动扭转成功，数据跟新到redis成功");
        }
    }

    private Boolean convertEvent(DrawPrizesData param, Map<String, AbstractOperate> map, int sequence) {

        //遍历map把sequence==1的执行
        Iterator<Map.Entry<String, AbstractOperate>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            //获得了一个实现类
            AbstractOperate value = iterator.next().getValue();

            if (value.sequence() != sequence
                    || !value.needConvert(param)) {
                log.info("不需要改变状态 key= {}", value.getClass().getName());
                continue;
            }

            if (!value.convert(param)) {
                log.info("改变状态失败了");
                throw new ServerException(ServerConstantCode.CONVERT_STATUS_ERROR);
            }

            //删除当前的
            iterator.remove();
        }

        return true;
    }
}
